<?php
namespace control;
/*
*会议室使用记录类
*/

class meetingRecordClass extends adIndexClass
{
    private const page = 'meetingRecord';
    private const table = 'meeting_record';
    private const tableMx = 'meeting_record_detail';
    private const title = '会议室使用记录';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => "会议编号",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "会议类别",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'theme'  => [
                        'name'  => "会议主题",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'meetingDate'         => [
                        'name'  => '会议时间',
                        'width' => 300,
                    ],
                    'room'          => [
                        'name'  => '会议室',
                        'width' => 100,
                    ],
                    'staffId'    => [
                        'name'  => '发起人',
                        'width' => 100,
                    ],
                    'deptName'    => [
                        'name'  => '发起人部门',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'people'    => [
                        'name'  => '参会人数',
                        'width' => 200,
                    ],
                    'state'    => [
                        'name'  => '状态',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会议编号" => text(array("name" => "orderNo")),
                    "会议类别"     => select(array('name' => 'type', 'option' => explode('，', para('meetingType')))),
                    "会议主题"     => text(array("name" => "theme")),
                ],
                [
                    '会议室'   => selectMultiple(array("name" => "roomId", "table" => "meeting_room", 'sqlField' => 'name', 'sqlId' => 'id')),
                    '发起人'   => selectMultiple(array("name" => "staffId", "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid')),
                    "会议开始时间" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        /*$url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=room')\" class='spanButton'>新增</span>\n";
        }*/
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//会议编号
            "theme" => $this->post('theme'),//会议主题
        );
        //全等查询数组
        $equal = array(
            "roomId" => $this->post('roomId'),//会议室
            "type" => $this->post('type'),//会议类别
            "state" => $this->post('state'),//状态
            "stid" => $this->post('staffId'),//发起人

        );
        $and = $this->seeSelf(self::page, 'stid');
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'meetingDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "staffId":
                        $row[] = self::findStaff($array['staffId']);
                        break;
                    case "meetingDate":
                        $row[] = $array['meetingDate'] . ' ' . $array['startTime'] . '至' . $array['meetingDate'] . ' ' . $array['endTime'];
                        break;
                    case "room":
                        $room = query('meeting_room', " id = '$array[roomId]'");
                        $row[] = $room['name'];
                        break;
                    case "people":
                        $people = static::total(array('table' => self::tableMx, 'where' => " and orderId = '$array[id]'"));
                        $row[] = $people;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $total    = [
            'people'        => static::total(array('table' => self::tableMx, 'where' => " and orderId in (select id from ".self::table." where 1=1 {$where})")),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 会议室申请图
     * @return string
     */
    public function room(): string
    {
        $toDay = $this->date;
        $data['html'] = <<<efo
<div style="width: 95%;margin: 10px auto;padding: 0 20px">选择空闲时段的会议室</div>
<div class="calendarBody">
<div class="calendarTitle"><span id="pre-button" class="pre-next-button" data-type="pre"><</span><span  id="calendar-date" class="calendar-date">{$toDay}</span><input type="hidden" name="toDate" value="$toDay"><span id="next-button" data-type="next" class="pre-next-button" style="margin-left: 10px"> ></span></div>
<div class="calendarContent">
</div>
</div>
<script>
 $(function() {
      request();
      laydate.render({elem:'#calendar-date', trigger:'click'});
   $(".calendarContent ").on('click','.click-line td',function(e) {
      let edit = $(this).data('edit');
      if (edit ===1){
            let roomId = $(this).data('id');
            let datetime = $(this).data('date');
            layer('meetingRecord','roomModel',{roomId:roomId,datetime:datetime});
      }
   });
     $("#next-button,#pre-button").click(function() {
        request($(this));
     })
     function request(e){
         let type = e?e.data('type'):'';
         let date = $("[name='toDate']").val();
         $.post(root+'control/adIndex.html?cla=meetingRecord&fun=calendar',{type:type,date:date},function(res) {
            if(res.warn ==2){
                $(".calendarContent").empty().append(res.html);
                $(".calendar-date").html(res.data.date);
                $("[name='toDate']").val(res.data.date);
            }else{
                warn(res.warn);
            }
        },'json')
     }
 })

</script>
<style>
.calendarContent{
 width: 97%;
 margin: 0 auto;
 padding-bottom: 20px
}
.pre-next-button{
 cursor: pointer;
 margin-right: 10px;
 font-size: 19px;
 font-weight: bold
}
.calendar-date{
font-weight: bold;font-size: 17px
}
.calendarBody{
 width: 95%;
 border: 1px solid rgb(230, 230, 230);
 margin: 10px auto
}
.calendarTitle{
 width: 100%;
 height: 50px;
 text-align: center;
 line-height: 50px
}
.click-line td{
 cursor: pointer;
}
.choiceDiv{
  position: absolute;
 width: 170px;
 background-color: #FFFFFF;
 box-shadow: rgb(230 230 230) 5px 5px 3px;
}
.choiceDivNav{
 cursor: pointer;
 height: 35px;

}
.dayTable{
border-collapse: collapse;
    border-spacing: 0;
}
.dayTable td {
    border: 1px solid rgb(230, 230, 230);
    word-break: break-all;
}
.rest-day{
  background-color: #4C9CFB;
}
.no-edit{
background-color: #F8F8F8
}
.choiceDivNav ul li {
 float: left;
 width: 47%;
 text-align: center;
 padding: 5px 2px;
}

.show-li{
 border-bottom: 2px solid #4C9CFB;
}
.choice-content ul li{
  padding: 3px 15px;
}
.choice-content ul li:hover {
    cursor: pointer;
    background-color: rgb(230, 230, 230);
}
.cycle-content ul li{
  padding: 3px 15px;
}
.cycle-content ul li:hover {
    cursor: pointer;
    background-color: rgb(230, 230, 230);
}
.choice-content,.cycle-content{
display: none;
}
.showContent{
 display: block;
}
.blueBackGroundColor{
  background-color: #4C9CFB !important;
  color:white;
}
</style>
efo;

        //返回
        return $this->tab($data);
    }

    public function calendar(): string
    {
        $type = $this->post('type');
        $toDay = $this->post('date') ?: $this->date;
        if ($type == 'pre') {
            //昨天
            $toDay = date('Y-m-d', strtotime("-1 day", strtotime($toDay)));
        } elseif ($type == 'next') {
            //明天
            $toDay = date('Y-m-d', strtotime("+1 day", strtotime($toDay)));
        }
        $month_half = [':00:00', ':30:00'];
        //总天数
        $hours = 24;//24小时分两个半点
        $dayHtml = "<tr class='no-edit'><td>分类</td><td>名称</td>";
        for ($i = 1; $i <= $hours; $i++) {
            $dayHtml .= "<td colspan='2'>{$i}</td>";
        }
        $dayHtml .= "</tr>";
        $memberArr = find(array('table' => 'meeting_room', 'where' => "state = '正常' order by time asc"));
        $peopleHtml = '';
        if (is_array($memberArr['array'])) {
            foreach ($memberArr['array'] as $array) {
                $peopleHtml .= "<tr class='click-line'><td>{$array['type']}</td><td>{$array['name']}</td>";
                for ($i = 1; $i <= $hours; $i++) {
                    for ($minute = 0; $minute < 2; $minute++) {
                        $datetime = $toDay . ' ' . sprintf('%02d', $i) . $month_half[$minute];
                        $roomRecord = query('meeting_record', "concat(meetingDate,' ',startTime,':00')<='$datetime' and concat(meetingDate,' ',endTime,':00')>'$datetime' and roomId = '$array[id]' and state !='草稿' order by time asc");
                        if (!empty($roomRecord['id'])) {
                            $staffName = self::findStaff($roomRecord['staffId']);
                            $startTime = $roomRecord['meetingDate'] . ' ' . $roomRecord['startTime'];
                            $endTime = $roomRecord['meetingDate'] . ' ' . $roomRecord['endTime'];
                            $title = "发起人：{$roomRecord['deptName']}-{$staffName}\n会议时间：{$startTime}至{$endTime}\n会议主题：{$roomRecord['theme']}";
                            //已占用
                            $peopleHtml .= "<td class='rest-day' title='$title' data-date='{$datetime}' data-id='$array[id]' data-edit='0' data-id='rest'></td>";
                        } else {
                            $edit = 1;
                            $class = '';
                            $peopleHtml .= "<td class='{$class}'  data-edit='{$edit}' data-date='{$datetime}' data-id='$array[id]'></td>";
                        }
                    }

                }
                $peopleHtml .= "</tr>";
            }
        }
        $json['data'] = [
            'date' => $toDay
        ];
        $json['html'] = <<<eof

<table class="dayTable">
{$dayHtml}
{$peopleHtml}
</table>
eof;
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 新增
     * @return bool|string
     */
    public function roomModel(): bool|string
    {
        $roomId = $this->post('roomId');
        $datetime = $this->post('datetime');
        $startTime = date('H:i', strtotime($datetime));
        $meetingDate = date('Y-m-d', strtotime($datetime));
        $room = query('meeting_room', "id = '$roomId'");
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            [
                must . "会议室：" => $room['name'] . '(' . $room['location'] . ')',
                "会议类别：" => select(array('name' => 'type', 'title' => '会议类别', 'option' => explode('，', para('meetingType')), 'value' => '')),
            ],
            [
                must . "会议主题：" => text(array('name' => 'theme', 'value' => '')),
                must . "会议日期：" => text(array('name' => 'meetingDate', 'laydate' => [], 'value' => $meetingDate)),
            ],
            [
                must . "会议时间：" => select(array('name' => 'startTime', 'title' => '请选择', 'option' => $this->period(), 'value' => $startTime)) . "\n至" . select(array('name' => 'endTime', 'title' => '请选择', 'option' => $this->period(), 'value' => '')) . "<div>".componentClass::tipComponent('会议时长不低于0.5h,不超过8h')."</div>"
            ],
            [
                "会议内容概述：" => textarea(array('name' => 'content', 'class' => 'textarea', 'value' => '')),
            ],
        ),
            'hidden' => hidden(array('name' => 'roomId', 'value' => $this->post('roomId'))),
        ));
        //返回
        return $this->layer(array(
            "title" => "新增",
            "height" => 400,
            "width" => 800,
            "html" => $html,
            'button' => '<button class="button" onclick="subForm(\'meetingRecordRoomModelForm\',root+\'control/adIndex.html?cla=meetingRecord&fun=roomEdit\')">保存</button>'
        ));
    }

    public function roomEdit(): bool|string
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'type' => $this->post('type'),
            'theme' => $this->post('theme'),
            'meetingDate' => $this->post('meetingDate'),
            'startTime' => $this->post('startTime'),
            'endTime' => $this->post('endTime'),
            'roomId' => $this->post('roomId'),
            'content' => $this->post('content'),
        ];
        $annotation = [
            'theme' => '会议主题',
            'meetingDate' => '会议日期',
            'startTime' => '会议时间',
            'endTime' => '会议时间',
            'roomId' => '会议地点',
        ];
        $rules = [
            'theme' => 'required',
            'meetingDate' => 'required',
            'startTime' => 'required',
            'endTime' => 'required',
            'roomId' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $startTime = $field['meetingDate'] . ' ' . $field['startTime'] . ':00';
        $endTime = $field['meetingDate'] . ' ' . $field['endTime'] . ':00';
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (strtotime($endTime) < strtotime($startTime)) {
            $json['warn'] = '结束时间不能小于开始时间';
        } elseif ($this->is_cross($startTime, $endTime, $field['roomId'])) {
            //判断提交时间是否和已申请的会员室时间存在重合
            $json['warn'] = '您所提交的使用时间和此会议室即将使用的时间有重合，请重新选择时间';
        } elseif (empty($id)) {
            $json['warn'] = '未找到ID';
        } else {
            $isPass = true;
            $this->startTrans();
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'MT' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'staffId' => $this->control['stid'],
                    'deptName' => $department['name'],
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }

            if ($isPass && in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();

        $info = query(self::table, " id = '" . $id . "' ");
        $button = [];
        if ($this->power(self::page, "edit")) {
            //按钮
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "cla" => $this->get('cla'),
                "fun" => "subForm('" . self::page . "EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
                "post" => ["id" => $this->get('id')],
                'style' => 'li-btn-blue-bg',
            ];
        }

        /*****参会人员*********/
        $tr[] = ['', '姓名', '部门', '职位', '联系电话'];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '{$info['id']}' order by list asc"));
        foreach ($result['array'] as $k=>$array) {
            $staff = query('staff', " stid = '$array[stid]'");
            $job = query('job', " id = '$array[jobId]'");
            $department = query('department', " id = '$job[departmentId]'");
            $tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this)").
                hidden(array('name' => 'mxId[]', 'value' => $array['stid'])),
                $staff['name'],
                $department['name'],
                $job['name'],
                $array['contactTel'],
            ];
        }

        $room = query('meeting_room', "id = '$info[roomId]'");
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    "会议类别：" => $info['type'],
                    must . "会议主题：" => $info['theme'],
                    must . "会议日期：" => $info['meetingDate'],
                    must . "会议时间：" => $info['startTime'] . "\n至" . $info['endTime'] . componentClass::tipComponent('会议时长不低于0.5h,不超过8h')
                ],
                [
                    must . "会议室：" => $room['name'] . '(' . $room['location'] . ')',
                ],
                [
                    "会议内容概述：" => pre($info['content']),
                ],
            ]
        ]);
        $mxButton      = "<span class='smallButton' onclick=\"layer('" . self::page . "','choose',{})\">添加</span>";
        $body .= $this->editList([
            'class' => 'staffMx',
            'title' => '参会人员',
            'button' => $mxButton,
            'html' => $this->listTable(array('tr' => $tr, 'end' => true)),
        ]);
        $body .= $this->editBlock([
            '附件' => fileUploadClass::addFileComponent($info['id'], '会议室使用记录', self::page, self::page . 'EditForm')
        ]);

        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
        ]);

        $data['html'] .= <<<efo

<script>
 //添加一行
         function addRow(){
             let stid = $("[name='chooseStid']").val();
             $('#meetingRecordChoose').hide();
             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{stid:stid},function (res){
                 $('.staffMx tbody').append(res.data);
                 resetNumber($('.staffMx'))
             },'json');
         }

</script>


efo;
        //返回
        return $this->tab($data);
    }

    /**
     * 生成下拉时间段
     * @param string $start
     * @param string $end
     * @return array
     */
    public function period($start = '00:00', $end = '23:30'): array
    {
        $arr = [];
        for ($i = strtotime($start); $i <= strtotime($end); $i = $i + 60 * 30) {
            $arr[] = date("H:i", $i);
        }
        return $arr;
    }

    /**
     *选择参会人员
     */
    public function choose()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "参会人员：" => selectMultiple(array("name" => "chooseStid", "title" => "参会人员", "table" => "staff", 'where' => "state not in ('离职')", 'sqlField' => 'name', 'sqlId' => 'stid'))
            ),
        )
        ));
        //返回
        return $this->layer(array(
            "title" => "参会人员",
            'winFix' => 1,
            "height" => 165,
            "html" => $html,
            'button' => "<input onclick='addRow()' type='button' class='button' value='确认'>"
        ));
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $staff = query('staff', " stid = '{$this->post('stid')}'");
        $job = query('job', " id = '$staff[jobId]'");
        $department = query('department', " id = '$job[departmentId]'");
        $tr[] = [
            componentClass::tablePperation('',"delTableRow(this)").
            hidden(array('name' => 'mxId[]', 'value' => $staff['stid'])),
            $staff['name'],
            $department['name'],
            $job['name'],
            $staff['tel'],
        ];
        $json['data'] = $this->tableMany(array('tr' => $tr, 'thead' => false));;
        return json_encode($json, 320);
    }


    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //参会人员
        $stidArr = $this->post('mxId') ?? [];
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此记录';
        } elseif (static::is_null_array($stidArr)) {
            $json['warn'] = '请选择参会人员';
        } else {
            $isPass = true;
            $this->startTrans();
            //添加或更新参会人员
            foreach ($stidArr as $nid) {
                $staff = query('staff', " stid = '$nid'");
                if (static::total(array('table' => self::tableMx, 'where' => " and stid = '$nid' and orderId ='$id'")) > 0) {
                    //更新
                    $warn = static::update([
                        "table" => self::tableMx,
                        "field" => [
                            'jobId' => $staff['jobId'],
                            'contactTel' => $staff['tel'],
                        ],
                        "where" => " orderId = '$id' and stid = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::tableMx,
                        "field" => [
                            'id' => self::getId(),
                            'orderId' => $id,
                            'stid' => $nid,
                            'jobId' => $staff['jobId'],
                            'contactTel' => $staff['tel'],
                            'updateTime' => $this->time,
                            'time' => $this->time
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $isPass = false;
                    $json['warn'] = $warn;
                    break;
                }
            }
            if ($isPass) {
                $this->commitTrans();
                //删除不在此ID中的数据
                delete(array('table' => self::tableMx, 'where' => " stid not in ('" . implode("','", $stidArr) . "') and orderId = '$id'"));
                //添加日志
                $text = $this->control['name'] . "更新了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '更新成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $json['warn'] = '更新失败';
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 判断是否和还未开始使用的会议室使用时间有重合
     */
    public function is_cross($startTime, $endTime, $roomId): bool|array
    {
        $flag = false;
        //还未开始使用的会议室
        $obj = new workSignCheckClass();
        $result = find(array('table' => 'meeting_record', 'where' => " roomId = '$roomId' and state !='草稿' and UNIX_TIMESTAMP(CONCAT_WS(' ',meetingDate,startTime)) > UNIX_TIMESTAMP() order by meetingDate desc,time desc"));
        foreach ($result['array'] as $array) {
            $startPlanTime = $array['meetingDate'] . ' ' . $array['startTime'] . ':00';
            $endPlanTime = $array['meetingDate'] . ' ' . $array['endTime'] . ':00';
            $bool = $obj->timeBetween($startTime, $endTime, $startPlanTime, $endPlanTime);
            if ($bool['isBetween']) {
                $flag = $bool['isBetween'];
                break;
            }
        }
        return $flag;
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
          if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '会议室申请',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );
            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => self::title,
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],

                ];
            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //审核按钮
            $button = array_merge($this->auditButton($info),$button);

            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
            $tr[] = ['姓名', '部门', '职位', '联系电话'];
            foreach ($result['array'] as $array) {
                $staff = query('staff', " stid = '$array[stid]'");
                $job = query('job', " id = '$array[jobId]'");
                $department = query('department', " id = '$job[departmentId]'");
                $tr[] = [$staff['name'], $department['name'], $job['name'], $array['contactTel']];
            }

            $room = query('meeting_room', " id = '$info[roomId]'");

            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        "会议类别" => $info['type'],
                        "会议主题" => $info['theme'],
                        "会议时间" => $info['meetingDate'] . ' ' . $info['startTime'] . '至' . $info['meetingDate'] . ' ' . $info['endTime'],
                        "会议时长（h）" => $this->hours($info['meetingDate'] . 'T' . $info['startTime'] . ':00', $info['meetingDate'] . 'T' . $info['endTime'] . ':00'),
                    ),
                    array(
                        "会议地点" => $room['name'] . " ({$room['location']})",
                        "发起人" => self::findStaff($info['staffId']),
                        "发起人部门" => $info['deptName'],
                    ),
                    array(
                        "会议内容概述" => pre($info['content']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '参会人员',
                'html' => "<div class='staffMx'><form name='detailForm'>" . hidden(array('name' => 'id', 'value' => $info['id'])) . $this->listTable(array('tr' => $tr, 'showSort' => true)) . "</form></div>",
            ]);
            $data['html'] .= $this->tableShow(array(
                '附件' => array(
                    array(
                        fileUploadClass::showFile($info['id'], '会议室使用记录')
                    )
                ),
                '会议内容' => array(
                    array(
                        "会议编号" => $info['orderNo'],
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "更新时间" => $info['updateTime'],
                    ),
                    array(
                        "状态" => $info['state'],
                    ),
                ),
                '流程' => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id'])
                    )
                ),

            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    public function hours($startTime, $endTime)
    {
        $t1 = strtotime($startTime);
        $t2 = strtotime($endTime);
        $diff = $t2 - $t1;
        return $diff / (60 * 60);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {

            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
